package com.spider.im.common.utils;

import cn.hutool.core.util.StrUtil;
import com.spider.im.common.aspect.BusinessException;
import com.spider.im.common.constant.RespCodeEnum;
import io.netty.util.internal.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

@Slf4j
@Component
public class EncryptionUtils {

    private final SecretKeySpec secretKey;

    public EncryptionUtils(@Value("${app.encryption.key}") String base64Key) {
        byte[] decodedKey = Base64.getDecoder().decode(base64Key);
        this.secretKey = new SecretKeySpec(decodedKey, "AES");
    }

    /**
     * 加密字符串
     *
     * @param data 要加密的数据
     * @return 加密后的Base64编码字符串
     */
    public String encrypt(String data) {
        try {
            if (StrUtil.isBlank(data)) {
                return null;
            }
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedBytes = cipher.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            log.error("Encryption failed {}", ThrowableUtil.stackTraceToString(e));
            throw new BusinessException(RespCodeEnum.ENCRYPT_ERROR, e);
        }
    }

    /**
     * 解密字符串
     *
     * @param encryptedData 加密后的Base64编码字符串
     * @return 解密后的原始字符串
     */
    public String decrypt(String encryptedData) {
        try {
            if (StrUtil.isBlank(encryptedData)) {
                return null;
            }
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes);
        } catch (Exception e) {
            log.error("Decryption failed{}", ThrowableUtil.stackTraceToString(e));
            throw new BusinessException(RespCodeEnum.DECRYPT_ERROR, e);
        }
    }


    public static String getEncodeKey() throws NoSuchAlgorithmException {
        // 创建AES密钥生成器
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128); // 使用128位密钥

        // 生成密钥
        SecretKey secretKey = keyGen.generateKey();

        // 将密钥转换为Base64编码字符串
//        String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());

    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        // 测试加密和解密
        String originalString = "password";
//        String encodeKey = EncryptionUtils.getEncodeKey();
//        System.out.println("EncodeKey : " + encodeKey);
        String encodeKey = "6bhZdGzjKUHsQ2kuhJdrjQ==";
        String encryptedString = new EncryptionUtils(encodeKey).encrypt(originalString);
        String decryptedString = new EncryptionUtils(encodeKey).decrypt(encryptedString);

        System.out.println("Original: " + originalString);
        System.out.println("Encrypted: " + encryptedString);
        System.out.println("Decrypted: " + decryptedString);
    }


}
